package com.ehuoyun.ecstore.action;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;

import com.ehuoyun.ecstore.biz.UserMgr;
import com.ehuoyun.ecstore.model.User;

/**
 * ActionBean that handles the registration of new users.
 *
 * @author Lilong Yao
 */
public class RegisterActionBean extends AbstractActionBean {
	
    @ValidateNestedProperties({
        @Validate(field="username", required=true, minlength=5, maxlength=20),
        @Validate(field="password", required=true, minlength=5, maxlength=20),
        @Validate(field="firstName", required=true, maxlength=50),
        @Validate(field="lastName", required=true, maxlength=50)
    })
    private User user;

    @Validate(required=true, minlength=5, maxlength=20, expression="this == user.password")
    private String confirmPassword;

    /** The user being registered. */
    public void setUser(User user) { this.user = user; }

    /** The user being registered. */
    public User getUser() { return user; }

    /** The 2nd/confirmation password entered by the user. */
    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    /** The 2nd/confirmation password entered by the user. */
    public String getConfirmPassword() { return confirmPassword; }

    @SpringBean
	private UserMgr userMgr;

	/**
     * Validates that the two passwords entered match each other, and that the
     * username entered is not already taken in the system.
     */
    @ValidationMethod
    public void validate(ValidationErrors errors) {
        if ( userMgr.getUser(this.user.getUsername()) != null ) {
            errors.add("user.username", new LocalizableError("usernameTaken"));
        }
    }

    /**
     * Registers a new user, logs them in, and redirects them to the bug list page.
     */
    @DefaultHandler
    public Resolution register() {
		try {
			String password = user.getPassword();
			MessageDigest m = MessageDigest.getInstance("MD5");
			m.update(password.getBytes(), 0, password.length());
			new BigInteger(1, m.digest()).toString(16);
			user.setPassword(password);
	        getContext().getRequest().getSession().setAttribute("user", this.user);
	        getContext().getMessages().add(
	                new LocalizableMessage(getClass().getName() + ".successMessage",
	                                       this.user.getFirstName(),
	                                       this.user.getUsername()));
	        userMgr.save(user);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
        return new RedirectResolution("/index.jsp");
    }
}
